package nc.bs.bd.pfxx.translator;

import nc.bs.dao.BaseDAO;
import nc.bs.pfxx.ITranslateContext;
import nc.bs.pfxx.ITranslatorStrategy;
import nc.bs.sec.esapi.NCESAPI;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.vo.pfxx.exception.PfxxException;
import nc.vo.pub.BusinessException;

public class StorTranslator implements ITranslatorStrategy {

	private BaseDAO dao = new BaseDAO();

	@Override
	public String getStrategyDescription() {
		return null;
	}

	@Override
	public String translateExToNC(String srcValue, String metaDataID, ITranslateContext translateContext) throws PfxxException {
		if (translateContext.getTranslateRule() == 1){
			return srcValue;
		} else if (translateContext.getTranslateRule() == 2){
			return queryPkByField("def1", srcValue, translateContext);
		} else if (translateContext.getTranslateRule() == 3) {
			return queryPkByField("name", srcValue, translateContext);
		} else {
			return null;
		}
	}

	private String queryPkByField(String field, String srcValue, ITranslateContext translateContext) throws PfxxException {
		try {
			String sql = "select pk_stordoc from bd_stordoc where def1 = (select pk_supplier from bd_supplier where dr=0 and " + field + " = '" + NCESAPI.sqlEncode(srcValue) + "') and " + "pk_group " + " = '" + NCESAPI.sqlEncode((String)translateContext.getPk_group()) + "'";
			String code = (String)dao.executeQuery(sql, new ColumnProcessor());
			if(code == null || "".equals(code)){
				sql = "select pk_stordoc from bd_stordoc where def1 = (select pk_customer from bd_customer where dr=0 and " + field + " = '" + NCESAPI.sqlEncode(srcValue) + "') and " + "pk_group " + " = '" + NCESAPI.sqlEncode((String)translateContext.getPk_group()) + "'";
				code = (String)dao.executeQuery(sql, new ColumnProcessor());
			}
			return code;
		} catch (BusinessException e) {
			throw new PfxxException(e);
		}
	}


	@Override
	public String translateNCToEx(String docPk, String metaDataID, ITranslateContext translateContext) throws PfxxException {
		if (translateContext.getTranslateRule() == 1){
			return docPk;
		} else  if (translateContext.getTranslateRule() == 2){
			return queryFieldByPk("code", docPk, metaDataID);
		} else if (translateContext.getTranslateRule() == 3) {
			return queryFieldByPk("name", docPk, metaDataID);
		} else {
			return null;
		}
	}

	private String queryFieldByPk(String field, String docPk, String metaDataID) throws PfxxException {
		try {
			String sql = "select " + field + " from bd_stordoc where " + "pk_stordoc" + " = '" + NCESAPI.sqlEncode(docPk) + "'";
			return (String)dao.executeQuery(sql, new ColumnProcessor());
		} catch (BusinessException e) {
			throw new PfxxException(e);
		}
	}

}